<?php
if(!defined('SYSTEM_PATH' ) ) die('Cannot access this page directly or see your configuration file ' ) ;
if(!defined('AJAX_CODE'))
	define('AJAX_CODE', 'javascript') ;
if(!defined('AJAX_TEMP'))
	define('AJAX_TEMP', 'template') ;

/** 
* Ajaxcontroller
* 
* @desc		Allow to perform ajax operation
*
* @author 	menTiss
* @version 	1.0
*
* @date 		27/10/2007
*/
class Ajaxcontroller extends Cosmo {
	public 	$_isError = false ;
	private 	$_echo 	= null ;
	private	$_template= null ;

	/**
	 * Ajaxcontroller::__construct()
	 * 
	 * @desc Construct ajax controller and load method called, either search for index method. Use method _init for construct operation in child
	 * 
	 * @return void
	 */
	final public function __construct() {
		parent::__construct() ;
		
		$this->load->helper('ajax') ;
		$this->load->helper('javascript') ;
		
		$this->_init() ;
		
		if(isset($_GET['m']) && (method_exists(&$this, $_GET['m']))){
          	if(isset($_GET['data'] ) ) {
				$this->{$_GET['m']}($_GET['data'] ) ;
			} else {
				$this->{$_GET['m']}() ;
			}
          }elseif(!isset($_GET['m'] ) ) {
          	if(method_exists($this, 'index'))
				$this->index() ;
			else
				$this->_isError = true ;
          } else {
			$this->_isError 	 = true ;
		} 
	}
	/**
	 * Ajaxcontroller::_init()
	 * 
	 * @desc pseudo constructor
	 * 
	 * @return 
	 */
	public function _init() {}
	/**
	 * Ajaxcontroller::_add()
	 * 
	 * @desc Add a new line to display
	 * 
	 * @param string $string
	 * @return 
	 */
	public function _add($content, $type = AJAX_CODE) {
		if($type == AJAX_CODE)
			$this->_echo[] = (string)$content ;
		if($type == AJAX_TEMP)
			$this->_template[] = $content ;
	}
	/**
	 * Ajaxcontroller::_send()
	 * 
	 * @desc Prepare data to be displayed, reset the array display to null
	 * 
	 * @return string 
	 */
	public function _send() {
	
		if($this->_isError === true)
			return '' ;
	
		$string = '' ;
		if(is_array($this->_echo)) {
			reset($this->_echo) ;
			
			for($i=0;$i<count($this->_echo);$i++) {
				$string .= $this->_echo[$i] ;
			}
			unset($this->_echo) ;
			$this->_echo = null ;
		}
		if(is_array($this->_template)) {
			reset($this->_template) ;
			$template =& $this->load('template') ;
			$template->remove_all() ;
			for($i=0;$i<count($this->_template);$i++) {
				$template->add($this->_template) ;
			}
			unset($this->_template) ;
			$this->_template = null ;
			$string .= "\n html=".$this->template->getHtml() ;
		}		
		return $string;
	}
}
?>